package com.core {
import fairygui.GComponent;

/**
 * 碰撞类
 */
public class OBB extends GComponent {

	private var _axes:Vector.<Vector2> = new Vector.<Vector2>();
	protected var _extents:Array;
	private var _point:Vector2 = new Vector2();

	public function OBB() {
		super();
		rotation = 0;
	}

	/**
	 * 碰撞检测
	 * @param obb 要参与检测的对象
	 * @return
	 */
	public function detectorOBBvsOBB(obb:OBB):Boolean {
		var nv:Vector2 = this._point.sub(obb.point);
		var axisA1:Vector2 = _axes[0];
		if (this.getProjectionRadius(axisA1) + obb.getProjectionRadius(axisA1) <= Math.abs(nv.dot(axisA1))) return false;
		var axisA2:Vector2 = _axes[1];
		if (this.getProjectionRadius(axisA2) + obb.getProjectionRadius(axisA2) <= Math.abs(nv.dot(axisA2))) return false;
		var axisB1:Vector2 = obb.axes[0];
		if (this.getProjectionRadius(axisB1) + obb.getProjectionRadius(axisB1) <= Math.abs(nv.dot(axisB1))) return false;
		var axisB2:Vector2 = obb.axes[1];
		if (this.getProjectionRadius(axisB2) + obb.getProjectionRadius(axisB2) <= Math.abs(nv.dot(axisB2))) return false;
		return true;
	}

	override public function setSize(wv:Number, hv:Number, ignorePivot:Boolean = false):void {
		this._extents = [wv>>1, hv>>1];
		super.setSize(wv, hv, ignorePivot);
	}

	override public function set rotation(value:Number):void {
		super.rotation = value;
		value *= Math.PI / 180;
		_axes[0] = new Vector2(Math.cos(value), Math.sin(value));
		_axes[1] = new Vector2(-1 * Math.sin(value), Math.cos(value));
	}

	override public function set x(value:Number):void {
		super.x = value;
		this._point.setXY(this.displayObject.x, this.displayObject.y);
	}

	override public function set y(value:Number):void {
		super.y = value;
		this._point.setXY(this.displayObject.x, this.displayObject.y);
	}

	public function getProjectionRadius(axis:Vector2):Number {
		return this._extents[0] * Math.abs(axis.dot(this._axes[0])) +
				this._extents[1] * Math.abs(axis.dot(this._axes[1]));
	}

	public function get axes():Vector.<Vector2> {
		return _axes;
	}

	public function get point():Vector2 {
		return _point;
	}

}

}


class Vector2 {

	private var x:Number;
	private var y:Number;

	public function Vector2(x:Number=0, y:Number=0) {
		setXY(x, y);
	}

	public function setXY(x:Number, y:Number):void {
		this.x = x || 0;
		this.y = y || 0;
	}

	public function sub(v:Vector2):Vector2 {
		return new Vector2(this.x - v.x, this.y - v.y)
	}

	public function dot(v:Vector2):Number {
		return this.x * v.x + this.y * v.y;
	}

}


